package com.kxxnzstdsw.plugins

import com.kxxnzstdsw.exception.CanThrowException
import com.kxxnzstdsw.exception.ExceptionCode
import com.kxxnzstdsw.exception.NoThrowException
import com.kxxnzstdsw.exception.can.AuthenticationException
import com.kxxnzstdsw.exception.can.UnauthorizedException
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*

fun Application.configureException() {
  val log = log
  install(StatusPages) {
    exception<Throwable> { call, cause ->
      log.error(cause.message, cause)
      when (cause) {
        is AuthenticationException -> {
          call.error(cause, HttpStatusCode.Unauthorized)
        }

        is UnauthorizedException -> {
          call.error(cause, HttpStatusCode.Forbidden)
        }

        is CanThrowException -> {
          call.error(cause)
        }

        is NoThrowException -> {
          call.error("不可抛出异常", ExceptionCode.M_000001)
        }

        else -> {
          call.error("未知异常", ExceptionCode.M_000001, HttpStatusCode.InternalServerError)
        }
      }
    }
  }
}
